from models.admin.system.Menu import MenuTypeEnum
from schemas.common import Filter
from typing import List, Optional, Union

import models.admin.system.Admin as AdminModel
from core.Depend import check_token, has_permission

# 假设 original_data 是从数据库中查询到的 SQLModel 实例列表
async def assembl_routes(data, parent_id=0):
    authArr = []
    for item in data:
        if item.menu_type == MenuTypeEnum.BUTTON:
            authArr.append(item)
    

    def getAuths(menu_id):
        auths = []
        for auth in authArr:
            if auth.parent_id == menu_id:
                auths.append(auth.auths)
        return auths
    
    tree = []
    for item in data:
        # 使用 getattr 访问 SQLModel 实例的属性
        if getattr(item, "parent_id", 0) == parent_id:
            menu_type = getattr(item, "menu_type", 0)
            node = {}
            if menu_type == MenuTypeEnum.MENU:
                node = {
                    "component": getattr(item, "component",  getattr(item, "path", "")),
                    "path": getattr(item, "path", ""),
                    "name": getattr(item, "name", ""),
                    "redirect": getattr(item, "redirect", ""),
                    "meta": {
                        "icon": getattr(item, "icon", ""),  # 使用 getattr 获取属性
                        "title": getattr(item, "title", ""),
                        "extraIcon": getattr(item, "extra_icon", ""),
                        "roles": ["admin"] + [getattr(role, "code", "") for role in getattr(item, "roles", [])],
                        "auths": getAuths(item.id),
                        "rank": getattr(item, "rank", 0),
                        "frameSrc": getattr(item, "frameSrc", ""),
                        "frameLoading": getattr(item, "frame_loading", False),
                        "keepAlive": getattr(item, "keep_alive", False),
                        "hiddenTag": getattr(item, "hidden_tag", False),
                        "fixedTag": getattr(item, "fixed_tag", False),
                        "showLink": getattr(item, "show_link", False),
                        "showParent": getattr(item, "show_parent", False),
                        "transition":{
                            "enterTransition": getattr(item, "enter_transition", ""),
                            "leaveTransition": getattr(item, "leave_transition", "")
                        }
                    },
                    "children": await assembl_routes(data, getattr(item, "id"))
                }

                if item.parent_id == 0:
                    del node["component"]
                    del node["name"]
            elif menu_type == MenuTypeEnum.IFRAME:
                node = {
                    "path": getattr(item, "path", ""),
                    "name": getattr(item, "name", ""),
                    "component": getattr(item, "component",getattr(item, "path", "")),
                    "meta": {
                        "title": getattr(item, "title", ""),
                        "rank": getattr(item, "rank", 0),
                        "icon": getattr(item, "icon", ""),  # 使用 getattr 获取属性
                        "extraIcon": getattr(item, "extra_icon", ""),
                        "roles":  ["admin"] + [getattr(role, "code", "") for role in getattr(item, "roles", [])],
                        "frameSrc": getattr(item, "frame_src", ""),
                        "frameLoading": getattr(item, "frame_loading", False),
                        "keepAlive": getattr(item, "keep_alive", False),
                        "hiddenTag": getattr(item, "hidden_tag", False),
                        "fixedTag": getattr(item, "fixed_tag", False),
                        "showLink": getattr(item, "show_link", False),
                        "showParent": getattr(item, "show_parent", False),
                        "transition":{
                            "enterTransition": getattr(item, "enter_transition", ""),
                            "leaveTransition": getattr(item, "leave_transition", "")
                        }
                    }
                }
            elif menu_type == MenuTypeEnum.EXTERNAL_LINK:
                node = {
                    "path": getattr(item, "path", ""),
                    "name": getattr(item, "name", ""),
                    "meta": {
                        "rank": getattr(item, "rank", 0),
                        "title": getattr(item, "title", ""),
                        "icon": getattr(item, "icon", ""),  # 使用 getattr 获取属性
                        "extraIcon": getattr(item, "extra_icon", ""),
                        "roles": ["admin"] + [getattr(role, "code", "") for role in getattr(item, "roles", [])],
                        "showLink": getattr(item, "show_link", False),
                        "showParent": getattr(item, "show_parent", False),
                    }
                }

            # 如果没有子节点，或者子节点length==0，删除 children 属性
            if "children" in node:
                if not node["children"]:
                    del node["children"]

            if node:
                # 如果node redirect为空，删除 redirect 属性
                if "redirect" in node:
                    if not node["redirect"]:
                        del node["redirect"]
                # 如果node component为空，删除 component 属性
                if "component" in node:
                    if not node["component"]:
                        del node["component"]
                # 如果node meta extraIcon 为空，删除 extraIcon 属性
                if "extraIcon" in node["meta"]:
                    if not node["meta"]["extraIcon"]:
                        del node["meta"]["extraIcon"]
                # 如果frameSrc为空，删除 frameSrc frameLoading 属性
                if "frameSrc" in node["meta"]:
                    if not node["meta"]["frameSrc"]:
                        del node["meta"]["frameSrc"]
                        del node["meta"]["frameLoading"]
                # transition enterTransition 为空，删除 enterTransition 属性
                if "transition" in node["meta"]:
                    if "enterTransition" in node["meta"]["transition"]:
                        if not node["meta"]["transition"]["enterTransition"]:
                            del node["meta"]["transition"]
                if  getattr(item, "parent_id", 0) != 0:
                    if "rank" in node["meta"]:
                        del node["meta"]["rank"]
                    
                tree.append(node)
    return tree

async def convert_filter_values(conversion_map:dict,filters: Optional[List[Filter]] = [],dataLimit:Union[bool, str] = False,adminuser:AdminModel.redis_admin = None):
    """
    自动将过滤器列表中的字段值转换为适当的类型
    """

    for filter in filters:
        if filter.field in conversion_map:
            enum_class = conversion_map[filter.field]
            filter.value = enum_class(filter.value)

    if dataLimit != False and adminuser is not None:
        if dataLimit == "personal":
            filters.append(Filter(field="admin_id", operator="=", value=adminuser.admin.id))
        elif dataLimit == "auth":
            admin_ids = adminuser.admin_ids
            if 1 not in admin_ids:
                filters.append(Filter(field="admin_id", operator="in", value=admin_ids))

    return filters


